$(document).ready(function(){
	// 筛选条件下拉框初始化
	initFilters();
	
	// 筛选按钮
	$("#btnFilter").click(function(){
		filterRecords();
	});

	// 登记新学生按钮
	$("#bthAdd").click(function(){
		popupAddDialog();
	});
	
	// 对话框中的各下拉选择框初始化
	initDialogOptions();
	
	filterRecords();
});

function initFilters() {
	var urlBase = location.pathname;
	fnAddSelectOption("filterProject", urlBase + "/../../projects");
	fnAddSelectOption("filterCurrentAidStatus", urlBase + "/../../public/student-current-aid-statuses");
}

function fnAddSelectOption(objId, url) {
	var objMessage = $("#txtMessage");
	$.ajax({
		type: "GET",
		url: url,
		success: function(resp) {
			debugger
			if("0" == resp.code) {
				var objSelect = $("#" + objId);
				$.each(resp.data, function(index, item) {
					var value = ("code" in item) ? item.code : item.id;
					var optionHtml = "<option value='" + value + "'>" + item.name + "</option>";
					objSelect.append(optionHtml);
				});
			} else {
				objMessage.prepend("<div>请求" + url + "返回出错信息：" + resp.message + "</div>")
			}
		},
		error: function () { objMessage.prepend("<div>请求" + url + " 服务器处理请求出错，请联系IT运维人员。</div>") }
	});
}

function filterRecords() {
	var url = location.pathname + "/..";
	var projectId = $("#filterProject").val();
	var currentAidStatus = $("#filterCurrentAidStatus").val();
	var keyword = $("#keyword").val();
	var limit = $("#limit").val();
	limit = (typeof limit == "undefined" || limit == null || limit == "") ? 20 : limit;
	var page = $("#page").val();
	page = (typeof page == "undefined" || page == null || page == "") ? 1 : page;
	var postData = {projectId:projectId, status:currentAidStatus, keyword:keyword, page:page, limit:limit};
		
	$("#txtMessage").text("正在加载...")
    $.ajax({
        type: "GET",
        url: url,
        data: postData,
        dataType: "json",
        success: function (resp) {
            if (resp.code == "0") {
                var tableBodyObj = $("#tableStudents tbody");
                tableBodyObj.html("");
                $.each(resp.data.rows, function(index, item) {
                	var rowHtml = "<tr>";
                	rowHtml += "<td>" + item.sn + "</td>";
                	rowHtml += "<td>" + item.name + "</td>";
                	rowHtml += "<td>" + item.gender + "</td>";
                	rowHtml += "<td>" + item.regSemesterName + "</td>";
                	rowHtml += "<td>" + item.regSchool + "</td>";
                	rowHtml += "<td>" + item.regGradeName + "</td>";
                	rowHtml += "<td>" + item.status + "</td>";
                	rowHtml += "<td>";
                	//rowHtml += "<span class='clickable' onclick='exportPDF(" + item.id + ")'>PDF</span>";
                	rowHtml += "<span class='clickable' onclick='popupDetailsDialog(" + item.id + ")'>详情</span>";
                    rowHtml += "<span class='clickable' onclick='popupEditDialog(" + item.id + ")'>Edit</span>";
                	rowHtml += "</td>";
                	rowHtml += "</tr>";
                	tableBodyObj.append(rowHtml);
                });
                
                var countSummaryObj = $("#txtCountSummary");
                countSummaryObj.html("共 " + resp.data.total + " 条记录，当前为第 " + resp.data.page + " 页");

                var navObj = $("#pagingNav");
                var urlBase = url + "?keyword=" + keyword + "&limit=" + limit;
                var navHtml = genPagingNavHtml(urlBase, resp.data.total, limit, page);
                debugger
                navObj.html(navHtml);                
                
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        	$("#txtMessage").text("");
        },
        error: function () { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function navToPage(pageNumber) {
	$("#page").val(pageNumber);
	filterRecords();
}

//1.url pattern, 2.总记录数(resp.data.total)、每页多少行(limit)、当前第几页(page)
//以当前页为中心，前5页，后5页；判断最大最小边界
function genPagingNavHtml(urlBase, totalRows, pageSize, curPage) {
	var totalPages = Math.ceil(totalRows/pageSize);
	var step = 5;
	var min = curPage - 5;
	min = min<1 ? 1 : min;
	var max = min + 9;
	max = max>totalPages ? totalPages : max;

	var pagingHtml = "页码：";
	for(i=min; i<=max; i++) {
		if(i != curPage) {
			pagingHtml += "<span class='clickable' onclick='navToPage(" + i + ")'>" + i + "</span>";
		} else {
			pagingHtml += "<span>" + i + "</span>";
		}
	}
	
	return pagingHtml;
}


var studentDialog = $("#studentDialog").dialog({
    autoOpen: false,
    height:480,
    width: 400,
    modal: true,
	close: function() {}
});

function initDialogOptions() {
	var urlBase = location.pathname;
	fnAddSelectOption("studentDialog #projectId", urlBase + "/../../public/projects");
	fnAddSelectOption("studentDialog #regSemesterId", urlBase + "/../../public/semesters");
	fnAddSelectOption("studentDialog #gender", urlBase + "/../../public/genders");
	fnAddSelectOption("studentDialog #regGradeId", urlBase + "/../../public/grades");
	fnAddSelectOption("studentDialog #povertyLevel", urlBase + "/../../public/poverty-levels");

    var urlBasePublic = getAncestorPath(location.pathname, 2) + "public";
    fnAddSelectOption("studentEditDialog #projectId", urlBasePublic + "/projects");
    fnAddSelectOption("studentEditDialog #regSemesterId", urlBasePublic + "/semesters");
    fnAddSelectOption("studentEditDialog #gender", urlBasePublic + "/genders");
    fnAddSelectOption("studentEditDialog #regGradeId", urlBasePublic + "/grades");

}

function popupAddDialog() {
	// 各字段初始化，部分字段可保持上次操作的选项
    $("#studentDialog #id").val("");
    $("#studentDialog #name").val("");
    $("#studentDialog #gender").val("");
    $("#studentDialog #idNumber").val("");
    $("#studentDialog #regGradeId").val("");
    $("#studentDialog #contactPhone").val("");
    $("#studentDialog #contactWechat").val("");
    $("#studentDialog #contactEmail").val("");
    $("#studentDialog #contactOther").val("");
    $("#studentDialog #povertyLevel").val("");
    $("#studentDialog #suggestAmount").val("");
    $("#studentDialog #description").val("");
    
	studentDialog = studentDialog.dialog({
		label: "登记新学生",
	    buttons: {
	    	"提交登记信息": addStudent,
	    	Cancel: function() {
	    		studentDialog.dialog("close");
	    	}
	    }
	});
	studentDialog.dialog("open");
}

function addStudent() {
	var projectId = $("#studentDialog #projectId").val();
	var regSemesterId = $("#studentDialog #regSemesterId").val();
	var name = $("#studentDialog #name").val();
	var gender = $("#studentDialog #gender").val();
	var idNumber = $("#studentDialog #idNumber").val();
	var regSchool = $("#studentDialog #regSchool").val();
	var regGradeId = $("#studentDialog #regGradeId").val();
	var contactPhone = $("#studentDialog #contactPhone").val();
	var contactWechat = $("#studentDialog #contactWechat").val();
	var contactEmail = $("#studentDialog #contactEmail").val();
	var contactOther = $("#studentDialog #contactOther").val();
	var povertyLevel = $("#studentDialog #povertyLevel").val();
	var suggestAmount = $("#studentDialog #suggestAmount").val();
	var description = $("#studentDialog #description").val();
	var postData = {projectId:projectId, regSemesterId:regSemesterId, name:name, gender:gender, idNumber:idNumber, regSchool:regSchool, regGradeId:regGradeId, contactPhone:contactPhone, contactWechat:contactWechat, contactEmail:contactEmail, contactOther:contactOther, povertyLevel:povertyLevel, suggestAmount:suggestAmount, description:description};
	var url = location.href + "/..";
    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
            	studentDialog.dialog("close");
            	filterRecords(); // 刷新页面
                
            } else {
            	alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });    
}

function exportPDF(id) {
	var url = window.location.href + "/../exportPDF/"+ id;
	window.location.href = url;
} 

//学生信息和资助记录
var detailsDialog = $("#detailsDialog").dialog({
    autoOpen: false,
    height:560,
    width: 640,
    modal: true,
	close: function() {}
});

function popupDetailsDialog(studentId) {
	debugger
	var studentUrl = getAncestorPath(location.pathname,1) + studentId;
	ajaxGetData(studentUrl, showStudentInfo);
	var aidUrl = getAncestorPath(location.pathname,2) + "students-aids?studentId=" + studentId + "&page=1&limit=9999";
	ajaxGetData(aidUrl, showAidHistory);
}

function showStudentInfo(student) {
	var infoHtml = "";
	infoHtml += "姓名：" + student.name + " &nbsp; 性别：" + student.gender + " &nbsp; 身份证：" + student.idNumber + " &nbsp; id:" + student.id + "<br/>";
	infoHtml += "编号：" + student.sn + " &nbsp; 项目：" + student.projectName + " &nbsp; 登记学校：" + student.regSchool + " &nbsp; 登记年级：" + student.regGradeName + "<br/>";
	infoHtml += "联系方式：<br/>";
	infoHtml += "电话：" + student.contactPhone + " &nbsp; 邮箱：" + student.contactEmail + " &nbsp; 微信：" + student.contactWechat + "其他：" + student.contactOther + "<br/>";
	infoHtml += "备注：<br/><textarea rows='5' cols='90'>" + student.description + "</textarea>" 
	//debugger
	var infoDiv = $("#detailsDialog #studentInfo");
	infoDiv.html(infoHtml);

	// 重新绑定"增加资助记录"按钮
    $("#btnAddAidRecord").unbind("click");
    $("#btnAddAidRecord").click(function(){
        popupAddAidDialog(student.id, student.sn, student.name, student.projectId);
    });


    detailsDialog.dialog("open");
}


function showAidHistory(respData) {
	var tableBody =  $("#detailsDialog #aidTable tbody");
	tableBody.html("");
	debugger
    $.each(respData.rows, function(index, item) {
    	var rowHtml = "<tr>";
    	rowHtml += "<td>" + item.semesterName + "</td>";
    	rowHtml += "<td>" + item.school + "</td>";
    	rowHtml += "<td>" + item.gradeName + "</td>";
    	rowHtml += "<td>" + item.aidStatusName + "</td>";
    	rowHtml += "<td>" + item.aidAmount + "</td>";
    	rowHtml += "<td>" + item.receiptStatusName + "</td>";
    	rowHtml += "<td>" + item.summaryStatusName + "</td>";
    	rowHtml += "<td>" + item.sponsorName + "</td>";
    	rowHtml += "<td>" + item.remark + "</td>";
    	rowHtml += "</tr>";
    	tableBody.append(rowHtml);
    });
}

var aidDialog = $("#aidDialog").dialog({
    autoOpen: false,
    height:360,
    width: 360,
    modal: true,
    close: function() {}
});

function popupAddAidDialog(studentId, studentSn, studentName, projectId) {
    $("#aidDialog #studentId").val(studentId);
    $("#aidDialog #studentBrief").val(studentSn + " " + studentName);
    $("#aidDialog #project").val(projectId);

    if($("#aidDialog #aidStatus option").length <= 1) {
        var urlBase = getAncestorPath(location.pathname, 2);
        fnAddSelectOption("aidDialog #aidStatus", urlBase + "public/student-aid-statuses");
        fnAddSelectOption("aidDialog #aidType", urlBase + "public/student-aid-types");
        fnAddSelectOption("aidDialog #pairStatus", urlBase + "public/student-pair-statuses");
        fnAddSelectOption("aidDialog #grade", urlBase + "public/grades");
        fnAddSelectOption("aidDialog #semester", urlBase + "public/semesters");
        fnAddSelectOption("aidDialog #sponsorId", urlBase + "sponsors/list_for_selection");
        fnAddSelectOption("aidDialog #volunteerId", urlBase + "volunteers/list_for_selection");
	}

    aidDialog = aidDialog.dialog({
        label: "增加资助记录",
        buttons: {
            "确定": addAidRecord,
            Cancel: function() {
                aidDialog.dialog("close");
            }
        }
    });
    aidDialog.dialog("open");
}

function addAidRecord() {
    var studentId = $("#aidDialog #studentId").val();
    var semesterId = $("#aidDialog #semester").val();
    var projectId = $("#aidDialog #project").val();
    var school = $("#aidDialog #school").val();
    var gradeId = $("#aidDialog #grade").val();
    var aidAmount = $("#aidDialog #aidAmount").val();
    var aidStatus = $("#aidDialog #aidStatus").val();
    var aidType = $("#aidDialog #aidType").val();
    var pairStatus = $("#aidDialog #pairStatus").val();
    var sponsorId = $("#aidDialog #sponsorId").val();
    var volunteerId = $("#aidDialog #volunteerId").val();
    var remark = $("#aidDialog #remark").val();
    var url = getAncestorPath(location.pathname, 2) + "students-aids";
    var postData = {studentId:studentId, semesterId:semesterId, projectId:projectId, school:school, gradeId:gradeId, aidAmount:aidAmount, aidStatus:aidStatus, aidType:aidType, pairStatus:pairStatus, sponsorId:sponsorId, volunteerId:volunteerId, remark:remark};
    debugger

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
                aidDialog.dialog("close");
                // 刷新资助历史列表
                var aidUrl = getAncestorPath(location.pathname,2) + "students-aids?studentId=" + studentId + "&page=1&limit=9999";
                ajaxGetData(aidUrl, showAidHistory);
            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });
}

function popupEditDialog(studentId) {
    var studentUrl = getAncestorPath(location.pathname,1) + studentId;
    ajaxGetData(studentUrl, initStudentEditDialog);
}

var studentEditDialog = $("#studentEditDialog").dialog({
    autoOpen: false,
    height:480,
    width: 400,
    modal: true,
    close: function() {}
});


function initStudentEditDialog(student) {
    $("#studentEditDialog #id").val(student.id);
    $("#studentEditDialog #projectId").val(student.projectId);
    $("#studentEditDialog #regSemesterId").val(student.regSemesterId);
    $("#studentEditDialog #studentSn").text(student.sn);
    $("#studentEditDialog #regSchool").val(student.regSchool);
    $("#studentEditDialog #name").val(student.name);
    $("#studentEditDialog #gender").val(student.gender);
    $("#studentEditDialog #idNumber").val(student.idNumber);
    $("#studentEditDialog #regGradeId").val(student.regGradeId);
    $("#studentEditDialog #contactPhone").val(student.contactPhone);
    $("#studentEditDialog #contactWechat").val(student.contactWechat);
    $("#studentEditDialog #contactEmail").val(student.contactEmail);
    $("#studentEditDialog #contactOther").val(student.contactOther);
    $("#studentEditDialog #description").val(student.description);



    studentEditDialog = studentEditDialog.dialog({
        label: "修改学生信息",
        buttons: {
            "确定": updateStudentInfo,
            Cancel: function() {
                studentEditDialog.dialog("close");
            }
        }
    });
    studentEditDialog.dialog("open");

}

function updateStudentInfo() {
	var studentId = $("#studentEditDialog #id").val();
    var projectId = $("#studentEditDialog #projectId").val();
    var regSemesterId = $("#studentEditDialog #regSemesterId").val();
    var name = $("#studentEditDialog #name").val();
    var gender = $("#studentEditDialog #gender").val();
    var idNumber = $("#studentEditDialog #idNumber").val();
    var regSchool = $("#studentEditDialog #regSchool").val();
    var regGradeId = $("#studentEditDialog #regGradeId").val();
    var contactPhone = $("#studentEditDialog #contactPhone").val();
    var contactWechat = $("#studentEditDialog #contactWechat").val();
    var contactEmail = $("#studentEditDialog #contactEmail").val();
    var contactOther = $("#studentEditDialog #contactOther").val();
    var description = $("#studentEditDialog #description").val();
    var postData = {id:studentId, projectId:projectId, regSemesterId:regSemesterId, name:name, gender:gender, idNumber:idNumber, regSchool:regSchool, regGradeId:regGradeId, contactPhone:contactPhone, contactWechat:contactWechat, contactEmail:contactEmail, contactOther:contactOther, description:description};
    var url = getAncestorPath(location.pathname, 1) + studentId;

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(postData),
        dataType: "json",
        contentType:"application/json",
        success: function (resp) {
            if (resp.code == "0") {
                studentEditDialog.dialog("close");
                filterRecords(); // 刷新页面

            } else {
                alert("服务器返回出错信息：\n\n" + resp.message);
            }
        },
        error: function() { alert("Sorry，服务器处理请求出错，请联系IT运维人员。"); }
    });




}